<template>
  <div>
    <!-- 搜索栏 -->
    <search-bar @onSearch="onSearch"></search-bar>
    <!-- /搜索栏 -->
    <div class="itemHeadLeft">
      <el-icon size="24px"><Coin /></el-icon>
      <span>数据列表</span>
    </div>
    <el-button
      type="Info"
      @click="$router.push('/itemAdd')"
      :style="{ float: 'right' }"
      >添加</el-button
    >
    <el-button-group class="ml-4">
      <el-button type="info" color="green" @click="$router.push('/itemAdd')">导入数据</el-button>
      <el-button type="info" color="blue" @click="exportXlsx">导出数据</el-button>
    </el-button-group>
    <!--商品列表-->
    <el-table
      :data="items"
      style="width: 100%; margin-top: 15px; height: 500px"
    >
      <el-table-column prop="id" label="编号" width="70" />
      <el-table-column prop="icon" label="商品图片">
        <template #default="{ row }">
          <img :src="row.thumb" width="80" alt="" />
        </template>
      </el-table-column>
      <el-table-column prop="desc" label="商品描述">
        <template #default="{ row }">
          <el-tooltip effect="dark" placement="bottom">
            <template #content>
              <div style="width: 400px">{{ row.desc }}</div>
            </template>
            <span style="cursor: pointer">
              {{ row.desc.substr(0, 15) + "..." }}
            </span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="itemName" label="分类品牌"></el-table-column>
      <el-table-column prop="price" label="商品价格" />
      <el-table-column prop="sale" label="销量">
        <template #default="{ row }">
          <el-tag :color="row.sale > 500 ? 'rgb(246, 206, 8)' : 'rgb(103, 235, 8)'">
            {{ row.sale }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="onsale" label="标签">
        <template #default="{ row }">
          <el-switch
            v-model="row.onsale"
            style="
              --el-switch-on-color: #000fff;
              --el-switch-off-color: #aaaaaa;
            "
            :active-value="1"
            :inactive-value="0"
            @change="changeItemSaleState(row.id, row.onsale)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createAt" label="开售时间" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button
            size="small"
            @click="enterItemUpdate(row.id)"
            type="success"
            color="#fff000"
            >编辑</el-button
          >
          <el-button size="small" type="danger" color="#bbb111">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- /表格 -->
    <el-pagination
      layout="prev, pager, next, sizes, jumper, total"
      v-model:current-page="page"
      v-model:page-size="pageSize"
      background
      :total="total"
      @size-change="sizeChange"
      @current-change="pageChange"
    />
  </div>
</template>

<script>
import SearchBar from '@/components/SearchBar.vue'
import { renderItemLists, addMulItems } from '@a/itemLists'
import { read, utils, writeFileXLSX } from 'xlsx'
export default {
  name: 'itemLists',
  data () {
    return {
      items: [],
      total: 0,
      page: 1,
      pageSize: 10,
      searchParams: {
        keyWords: '',
        rangeDate: []
      }
    }
  },
  methods: {
    enterItemUpdate (id) {
      // 跳转到修改商品
      this.$router.push({
        path: '/itemUpdate',
        query: {
          id
        }
      })
    },
    exportXlsx () {
      // 导出excel模板
      // 模板数据
      const tplData = [
        {
          商品名字: '商品n',
          商品价格: 10,
          商品描述: '这是描述',
          商品销量: 10,
          商品封面: '',
          '上下架(1上架0下架)': 1
        }
      ]
      const ws = utils.json_to_sheet(tplData)
      const wb = utils.book_new()
      utils.book_append_sheet(wb, ws, 'Data')
      writeFileXLSX(wb, '商品模板.xlsx')
    },
    readXlsx (file) {
      // 获取 excel解析为 json数组
      // 将文件转换成arrayBuffer格式
      const fd = new FileReader()
      fd.readAsArrayBuffer(file)
      // 读取文件是异步的 设计 事件 监听异步 进程
      // onload在文件读取成功后触发 结果在 fd的result属性上
      fd.onload = () => {
        const wb = read(fd.result)
        const data = utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
        // json数组 字段 转换
        const data2 = data.map((el) => {
          return {
            itemName: el.商品名字,
            price: el.商品价格,
            desc: el.商品描述,
            sale: el.商品销量,
            thumb: el.商品封面,
            onsale: el['上下架(1上架0下架)']
          }
        })
        // 发送请求 给批量添加商品接口
        addMulItems({
          items: data2
        }).then((res) => {
          if (res.data.code === 200) {
            this.$message({
              type: 'success',
              message: res.data.msg,
              duration: 1500,
              onClose: () => {
                this.$router.go(0)
              }
            })
          }
        })
      }
      return false
    },
    fetchItems () {
      // 请求商品列表
      renderItemLists({
        page: this.page,
        pageSize: this.pageSize,
        keyWords: this.searchParams.keyWords,
        startTime: this.searchParams.rangeDate[0],
        endTime: this.searchParams.rangeDate[1]
      }).then((res) => {
        if (res.data.code === 200) {
          this.total = res.data.data.total
          this.items = res.data.data.lists
        }
      })
    },
    onSearch (searchParams) {
      this.searchParams = searchParams
      this.fetchItems()
    },
    sizeChange () {
      this.fetchItems()
    },
    pageChange () {
      this.fetchItems()
    }
  },
  created () {
    this.fetchItems()
  },
  components: {
    SearchBar
  }
}
</script>

<style lang="scss" scoped>
.itemHeadLeft {
  margin-bottom: 15px;
}
</style>
